package com.tancire.web.controller.system;

import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import cn.hutool.crypto.symmetric.SymmetricCrypto;
import com.tancire.common.constant.Constants;
import com.tancire.common.core.domain.AjaxResult;
import com.tancire.common.core.domain.entity.SysMenu;
import com.tancire.common.core.domain.entity.SysUser;
import com.tancire.common.core.domain.model.LoginBody;
import com.tancire.common.core.redis.RedisCache;
import com.tancire.common.utils.SecurityUtils;
import com.tancire.common.utils.StringUtils;
import com.tancire.framework.web.service.SysLoginService;
import com.tancire.framework.web.service.SysPermissionService;
import com.tancire.net.domain.NetUser;
import com.tancire.net.service.INetUserService;
import com.tancire.net.utils.OpenidUtils;
import com.tancire.system.service.ISysMenuService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Base64;
import java.util.List;
import java.util.Set;

/**
 * 登录验证
 *
 * @author ruoyi
 */
@RestController
public class SysLoginController {
    @Resource
    private SysLoginService loginService;

    @Resource
    private ISysMenuService menuService;

    @Resource
    private SysPermissionService permissionService;

    @Resource
    private OpenidUtils openidUtils;

    @Resource
    private INetUserService netUserService;

    @Resource
    private RedisCache redisCache;


    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody) {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid(), Constants.SYS_LOGIN);
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login/company")
    public AjaxResult companyLogin(@RequestBody LoginBody loginBody) {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid(), Constants.COMPANY_LOGIN);
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    /**
     * 微信登录
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login/wx")
    public AjaxResult wxLogin(@RequestBody LoginBody loginBody) {
        AjaxResult ajax = AjaxResult.success();
        String openid = loginBody.getUsername();
        // 生成令牌
        if (StringUtils.isBlank(openid)) {
            openid = openidUtils.getOpenid(loginBody.getCode());
        } else {
            // 解析username 获取openId
            try {
                Object cacheObject = redisCache.getCacheObject(Constants.JM_PREFIX + openid);
                String cacheObjectStr = (String) cacheObject;
                byte[] byteArray2 = Base64.getDecoder().decode(cacheObjectStr);
                SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, byteArray2);
                redisCache.deleteObject(Constants.JM_PREFIX + openid);
                openid = aes.decryptStr(openid);
            } catch (Exception e) {
                return AjaxResult.error("登录失败");
            }
        }
        if (StringUtils.isBlank(openid)) {
            return AjaxResult.error("登录失败");
        }
        NetUser netUser = netUserService.selectNetUserByOpenId(openid);
        if (null == netUser || null == netUser.getId()) {
            // 没有登录过，创建账号
            NetUser user = new NetUser();
            user.setAccount(IdUtil.getSnowflakeNextId() + "");
            user.setPassword(SecurityUtils.encryptPassword(IdUtil.fastSimpleUUID()));
            user.setOpenId(openid);
            netUserService.insertNetUser(user);
        }
        // 获取openId，用于登录
        String token = loginService.login(openid, Constants.NO_PASSWORD_CERTIFY, loginBody.getCode(),
                loginBody.getUuid(), Constants.WX_LOGIN);
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }


    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo() {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public AjaxResult getRouters() {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return AjaxResult.success(menuService.buildMenus(menus));
    }
}
